import 'package:bilibili/http/dao/login_dao.dart';
import 'package:bilibili/navigator/hi_navigator.dart';
import 'package:hi_common/util/logger.dart';
import 'package:bilibili/util/toast.dart';
import 'package:flutter/material.dart';
import 'package:hi_net/http/core/hi_error.dart';

class LoginPage extends StatefulWidget {
  LoginPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends State<LoginPage> {
  bool _isLoading = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("登录"),
        leading: const BackButton(),
        actions: [
          MaterialButton(
            child: const Text("注册"),
            onPressed: () {
              HiNavigator.getInstance().onJumpTo(RouteStatus.registration);
            },
          )
        ],
      ),
      body: Scaffold(
          body: Stack(
        children: [
          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                MaterialButton(
                  onPressed: () {
                    _send(() {
                      HiNavigator.getInstance().onJumpTo(RouteStatus.home);
                    });
                  },
                  child: const Text("登录"),
                )
              ],
            ),
          ),
          if (_isLoading)
            const Opacity(
              opacity: 0.7,
              child: ModalBarrier(
                dismissible: false,
                color: Colors.grey,
              ),
            ),
          if (_isLoading)
            const Center(
              child: CircularProgressIndicator(),
            )
        ],
      )),
    );
  }

  void _send(Function() onLoginSuccess) async {
    setState(() {
      _isLoading = false;
    });
    try {
      var response = await LoginDao.login(
          "慕课·小冰", "GjqGmnezG9.JYKTP.WJ9F2Wl7xJMdHmanihXkEmBFUBeAwAC20210301");

      setState(() {
        _isLoading = true;
      });
      if (response["code"] == 0) {
        logger.d(response);
        showToast("登录成功");
        onLoginSuccess();
      }
    } on AuthException catch (e) {
      logger.d(e);
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      logger.d(e);
      showWarnToast(e.message);
    }
  }
}
